<template>
    <div>
        <div class="list-box" style="min-height:500px;">
            <div class="pannel-title pannel-between">
                <div>{{ title }}</div>
            </div>
            <div class="line"></div>
            <div class="data-table article-content" v-show="pageLoading && formState.isDel === 'Y'">
                <div class="is_del">已删除</div>
                <h2>{{ formState.title }}</h2>
                <div class="article-info">
                    <span>作者：{{ formState.author }}</span>
                    <span>分类：{{ cateName }}</span>
                    <span>创建时间：{{ formState.createTime }}</span>
                </div>
                <div v-html="formState.content"></div>
                <a-button type="default" shape="round" @click="cancel()">返回</a-button>
            </div>
            <div class="data-table" v-show="pageLoading && (!formState.isDel || formState.isDel === 'N')">
                <div class="pannel-form">
                    <a-form ref="form1" :model="formState" :rules="rules" :labelCol="{ span: 4, offset: 0 }" :wrapperCol="{ span: 9, offset: 0 }">
                        <a-form-item label="标题" name="title">
                            <a-input v-model:value="formState.title" placeholder="请输入标题" />
                        </a-form-item>
                        <a-form-item label="作者" name="author">
                            <a-input v-model:value="formState.author" placeholder="请输入作者姓名" />
                        </a-form-item>
                        <a-form-item label="正文" name="content" :wrapperCol="{ span: 20, offset: 0 }">
                            <vue-ueditor-wrap @beforeInit="addCustomDialog" v-model="formState.content" :config="editorConfig" editor-id="editor-demo-01"></vue-ueditor-wrap>
							<upload-modal v-model:visible="visible" @imageChange="insertImage"></upload-modal>
						</a-form-item>
                        <a-form-item label="文章预览图" name="thumbnails">
                            <avatar-upload width="200px" height="120px" v-model:value="formState.thumbnails"></avatar-upload>
                            <a @click="showPicModal()">使用历史图片</a>
                        </a-form-item>
                        <a-form-item label="排序序号" name="displayPriority">
                            <a-input v-model:value="formState.displayPriority" placeholder="请输入大于等于0的正整数">
                                <template #suffix>
                                    <a-tooltip title="排序序号数值越小越靠前">
                                        <info-circle-outlined style="color: rgba(255, 0, 0, 0.7)" />
                                    </a-tooltip>
                                </template>
                            </a-input>
                        </a-form-item>
                        <a-form-item label="文章关键字" name="keywords">
                            <tag-input maxCount="5" placeholder="请输入关键字，回车确认,最多输入5个" v-model:value="formState.keywords"></tag-input>
                        </a-form-item>
                        <a-form-item label="阅览权限" name="isMember">
                            <a-radio-group name="radioGroup" v-model:value="formState.isMember">
                                <a-radio value="Y">会员可阅览</a-radio>
                                <a-radio value="N">不限制</a-radio>
                            </a-radio-group>
                        </a-form-item>
                        <a-form-item label="是否隐藏" name="isHide">
                            <a-select v-model:value="formState.isHide" :options="isHides" placeholder="请选择状态"></a-select>
                        </a-form-item>
                        <a-form-item label="分类" name="cateId">
							<a-select v-model:value="formState.cateId">
								<a-select-opt-group v-for="item in cateIds" :key="item.id" :label="item.name">
									<a-select-option v-for="child in item.children" :key="child.id" :value="child.id">{{child.name}}</a-select-option>
								</a-select-opt-group>
							</a-select>
						</a-form-item>
                        <a-form-item label="是否允许转载" name="allowReprint">
                            <a-select v-model:value="formState.allowReprint" :options="allowReprints" placeholder="请选择状态"></a-select>
                        </a-form-item>
                        <!-- <a-form-item label="logo" name="logo">
							<avatar-upload v-model:value="formState.logo"></avatar-upload>
						</a-form-item> -->
                    </a-form>
                    <a-modal width="1000px" title="历史图片" v-model:visible="visiblePic" :maskClosable="false" :footer="null" :afterClose="closePicModal">
                        <a-table :columns="columnsPic" :row-key="(record) => record.id" :scroll="{ x: 800, y: 400 }" :data-source="dataSourcePic" :pagination="pagesPic" :loading="picLoading" @change="changePagePic">
                            <template #thumbnails="{ text }">
                                <img style="width:160px;height:96px;border-radius:4px;" :src="text" />
                            </template>
                            <template #action="{ record }">
                                <a @click="selectPic(record.thumbnails)">使用图片</a>
                            </template>
                        </a-table>
                    </a-modal>
                </div>
                <div class="pannel-form-btn">
                    <a-button type="default" shape="round" @click="cancel()">返回</a-button>
                    <a-button v-if="showSubmin" :loading="btnLoading" type="primary" shape="round" @click="confirm()">提交</a-button>
                </div>
            </div>
        </div>
        <div class="list-box" style="margin-top: 5px" v-if="isShowCommentList">
            <div class="pannel-title pannel-between">
                <div>评价</div>
            </div>
            <!-- 評價列表 -->
            <div class="data-table">
                <a-table :columns="columns" :row-key="(record) => record.id" :data-source="commentList" :pagination="false" :loading="isLoading">
                    <template #action="{ record }">
                        <!-- <a title="编辑" style="margin-right:5px;"><router-link :to="{path:'/technicalArticleAdd',query:{id:record.id}}"> <img src="@/assets/images/cz-edit.png"/></router-link></a> -->
                        <a @click="deleteMenu(record)" title="删除"><img src="@/assets/images/cz-delete.png"/></a>
                        <!-- <a v-if="record.is_del == 'Y'" >已删除</a> -->
                    </template>
                    <template #time="{ text }">
                        {{ formatDate(text) }}
                    </template>
                </a-table>
            </div>
        </div>
    </div>
</template>
<script>
import { InfoCircleOutlined } from "@ant-design/icons-vue";
import { useStore } from "vuex";
import { ref,reactive } from "@vue/reactivity";
import { message, Button, Form, Input, Tooltip, Select, Table, Modal, Radio } from "ant-design-vue";
import httpRequest from "@/util/httpRequest";
import baseUtil from "@/util/baseUtil";
import tagInput from "@/components/tagInput";
import avatarUpload from "@/components/avatarUpload";
// import Upload from "@/util/upload";
import toolbar from "@/util/toolbar";
import UploadModal from "@/components/uploadModal/uploadModal";
export default {
    components: {
        InfoCircleOutlined,
        ATable: Table,
        AButton: Button,
        AForm: Form,
        AModal:Modal,
        AFormItem: Form.Item,
        AInput: Input,
        // AModal: Modal,
        ATooltip: Tooltip,
        ASelect: Select,
		ASelectOptGroup:Select.OptGroup,
		ASelectOption:Select.Option,
        ARadio: Radio,
        ARadioGroup: Radio.Group,
        tagInput,
        avatarUpload,
		UploadModal
    },
    setup() {
        const store = useStore();
        //text：页面头部面包屑的显示文字，isBack：是否显示页面头部返回按钮
        store.dispatch("setBreadcrumb", {
            text: "文章管理 / 技术文章",
            isBack: true,
        });
        const formState = ref({
            id: null,
            title: "",
            author: "",
            displayPriority: "0",
            cateId: "",
            // logo: "",
            content: "",
            allowReprint: "",
            isHide: "",
            isMember: "",
            keywords: "",
            editType: "HTML",
            thumbnails: "",
        });
        const allowReprints = ref([
            { value: "Y", label: "允许" },
            { value: "N", label: "不允许" },
        ]);
        const isHides = ref([
            { value: "Y", label: "隐藏" },
            { value: "N", label: "显示" },
        ]);
        const dataSourcePic = ref([]);
		const columnsPic = reactive([
			{
				title: "文章标题",
				dataIndex: "title",
				key: "title",
			},
			{
				title: "预览图",
				dataIndex: "thumbnails",
				key: "thumbnails",
                width:240,
				slots: { customRender: "thumbnails" },
			},
			{
				title: "操作",
				key: "action",
                width:100,
				slots: { customRender: "action" },
			},
		]);
		const pagesPic = ref({
			keywords: "",
			cateId1: 0,
			cateId2: 0,
			status: "",
			current: 1,
			pageSize: 10,
			total:0
		});
        return {
            formState,
            btnLoading: ref(false),
            cateIds: ref([]),
            cateList: ref([]),
            allowReprints,
            isHides,
			visible:ref(false),
			visiblePic:ref(false),
            editorConfig: ref({
                UEDITOR_HOME_URL: process.env.VUE_APP_BASEPATH === '/'? '/UEditor/': process.env.VUE_APP_BASEPATH + "/UEditor/",
				lang:"zh-cn",
                zIndex: 99,
                initialFrameWidth: 800,
                initialFrameHeight: 400,
                maximumWords:1000000,
                scaleEnabled: false,
				autoHeightEnabled:false,
				toolbars:[
					toolbar
				],
            }),
            dataSourcePic,
            columnsPic,
            pagesPic,
            picLoading:ref(false),
        };
    },
    data() {
        return {
            rules: {
                author: {
                    required: true,
                    message: "作者名称不能为空",
                    trigger: "blur",
                },
                cateId: {
                    required: true,
                    message: "不能为空",
                    trigger: "change",
                    type: "number",
                },
                title: {
                    required: true,
                    message: "文章标题不能为空",
                    trigger: "blur",
                },
                content: [
                    {
                        required: true,
                        message: "文章内容不能为空",
                        trigger: "blur",
                    },
                ],
                allowReprint: {
                    required: true,
                    message: "不能为空",
                    trigger: "blur",
                },
                isHide: {
                    required: true,
                    message: "不能为空",
                    trigger: "blur",
                },
                isMember: {
                    required: true,
                    message: "不能为空",
                    trigger: "change",
                },
                displayPriority: [
                    {
                        required: true,
                        message: "不能为空",
                        trigger: "blur",
                    },
                    {
                        trigger: "blur",
                        message: "请输入大于等于0的整数",
                        pattern: /^(0|[1-9]\d*)$/,
                    },
                ],
            },
            isLoading: false,
            pageLoading: true,
            title: "新增技术文章",
            showSubmin: true,
            isShowCommentList: false,
            commentList: [],
            pages: {
                page: 1,
                pageSize: 10,
            },
            columns: [
                {
                    title: "编号",
                    dataIndex: "id",
                    key: "id",
                },
                {
                    title: "用户ID",
                    dataIndex: "name",
                    key: "name",
                },
                {
                    title: "内容",
                    dataIndex: "comment",
                    key: "comment",
                },
                {
                    title: "发布时间",
                    dataIndex: "create_time",
                    key: "create_time",
                    slots: { customRender: "time" },
                },
                {
                    title: "操作",
                    key: "action",
                    slots: { customRender: "action" },
                },
            ],
			editor:null
        };
    },
    computed: {
        cateName() {
            let text = "";
            if (this.cateList && this.formState && this.formState.cateId) {
                const cate = this.cateList.filter((e) => e.id === this.formState.cateId);
                if (cate && cate.length > 0) {
                    text = cate[0].name;
                }
            }
            return text;
        },
    },
    mounted() {
        if (this.$route.query.id) {
            this.isShowCommentList = true;
            this.title = "編輯技术文章";
            this.pageLoading = false;
            httpRequest
                .post("获取技术文章详情", { id: this.$route.query.id })
                .then((res) => {
                    this.formState = { ...baseUtil.LineToHump(res.data) };
                    this.formState.keywords = this.formState.keywords.join(",");
                    this.formState.displayPriority = String(this.formState.displayPriority);
                    if (this.formState.isDel == "Y") {
                        this.showSubmin = false;
                    }
                })
                .finally(() => {
                    this.pageLoading = true;
                });
            this.pages.articleId = this.$route.query.id;
            httpRequest.post("获取技术文章评论列表", this.pages).then((res) => {
                this.commentList = res.data.data;
            });
        }else{
			this.formState.displayPriority = sessionStorage.getItem('displayPriority');
		}
        httpRequest.post("获取文章分类集合", { level: "1", type: "Tech" }).then((res) => {
            this.cateIds = baseUtil.GetByTree(res.data);
        });
    },
    methods: {
        confirm() {
            this.$refs.form1.validate().then(() => {
                this.btnLoading = true;
                const url = this.formState.id ? "编辑技术文章" : "创建技术文章";
                const msg = this.formState.id ? "修改成功" : "创建成功";
                if (!this.formState.id) {
                    delete this.formState.id;
                }
                httpRequest
                    .post(url, this.formState)
                    .then(() => {
                        this.$router.push("/technicalArticle");
                        message.success(msg);
                    })
                    .finally(() => {
                        this.btnLoading = false;
                    });
            });
        },
        closePicModal(){
            this.visiblePic = false;
        },
        changePagePic(e){
            this.pagesPic.current = e.current;
			this.getList();
        },
        showPicModal(){
            console.log(1);
            this.pagesPic.current = 1;
            this.getList();
            this.visiblePic = true;
        },
        selectPic(imgUrl){
            this.formState.thumbnails = imgUrl;
            this.visiblePic = false;
        },
        getList() {
			this.picLoading = true;
			httpRequest
				.post("获取技术文章列表",{...this.pagesPic,page:this.pagesPic.current})
				.then((res) => {
					this.dataSourcePic = res.data.data;
					this.pagesPic.total = res.data.total;
				})
				.finally(() => {
					this.picLoading = false;
				});
		},
        cancel() {
            this.$router.back();
        },
        deleteMenu(item) {
            Modal.confirm({
                title: "系统提示",
                content: "确认删除此评论？",
                okText: "删除",
                cancelText: "取消",
                onOk: () => {
                    return new Promise((res) => {
                        this.isLoading = true;
                        httpRequest
                            .post("删除技术文章评论", { id: item.id })
                            .then(() => {
                                message.success("成功删除评论！");
                                httpRequest.post("获取技术文章评论列表", this.pages).then((res) => {
                                    this.commentList = res.data.data;
                                });
                            })
                            .catch(() => {
                                message.warning({ content: "删除评论失败", key: "error" });
                            })
                            .finally(() => {
                                this.isLoading = false;
                                res();
                            });
                    });
                },
            });
        },
        formatDate(val) {
            return baseUtil.getTime(val);
        },
        onEditorChange(editor) {
            this.formState.content = editor.html;
        },
		insertImage(url){
			this.editor.execCommand("inserthtml", `<img src="${url}">`);
			console.log(url);
		},
        addCustomDialog(editorId) {
			const _that = this;
            window.UE.registerUI(
                "upload-button",
                function(editor, uiName) {
                    // 注册按钮执行时的 command 命令，使用命令默认就会带有回退操作
                    editor.registerCommand(uiName, {
                        execCommand: function() {
							_that.visible = true;
							_that.editor = editor;
                        },
                    });

                    // 创建一个 button
                    var btn = new window.UE.ui.Button({
                        // 按钮的名字
                        name: uiName,
                        // 提示
                        title: "插入图片",
                        // 需要添加的额外样式，可指定 icon 图标，图标路径参考常见问题 2
                        cssRules: "background-position: -380px 0px;",
                        // 点击时执行的命令
                        onclick: function() {
                            // 这里可以不用执行命令，做你自己的操作也可
                            editor.execCommand(uiName);
                        },
                    });

                    // 当点到编辑内容上时，按钮要做的状态反射
                    editor.addListener("selectionchange", function() {
                        var state = editor.queryCommandState(uiName);
                        if (state === -1) {
                            btn.setDisabled(true);
                            btn.setChecked(false);
                        } else {
                            btn.setDisabled(false);
                            btn.setChecked(state);
                        }
                    });

                    return btn;
                },
                56,
                editorId
            );
        },
    },
};
</script>
<style lang="less" scoped>
.line {
    width: 100%;
    margin: 20px 0;
    border-top: 1px solid #eee;
}
.article-content {
    position: relative;
    h2 {
        font-size: 26px;
        height: 60px;
        line-height: 60px;
    }
    .article-info {
        background: #fafafa;
        color: #888;
        padding: 10px;
        border-radius: 5px;
        margin-bottom: 30px;
        span {
            margin: 0 20px;
        }
    }
    .content {
        margin-bottom: 30px;
    }
    .is_del {
        width: 100px;
        height: 100px;
        border: 3px solid rgba(255, 0, 0, 0.2);
        border-radius: 50px;
        font-size: 24px;
        text-align: center;
        line-height: 100px;
        color: rgba(255, 0, 0, 0.3);
        transform: rotate(-30deg);
        position: absolute;
        right: 0;
        top: 0;
    }
}
</style>
